<?php
session_start();

$music_path = realpath(dirname(__FILE__) . '/../../_tmp/music/');

$f = $_FILES['Filedata'];

$fdir = date('/Y/m/');
$fname = $f['name'];

function rand_str($len=6) {
	// #%*
	$chars='ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789'; // characters to build the password from
	mt_srand((double)microtime()*1000000*getmypid()); // seed the random number generater (must be done)
	$password='';
	while(strlen($password)<$len)
		$password.=substr($chars,(mt_rand()%strlen($chars)),1);
	return $password;
}

function ftp_mkdir_recusive($con_id,$path){
	$fullpath = ftp_pwd($con_id);
	foreach(explode("/",$path) as $part){
		$fullpath .= $part."/";
		if(empty($part)){
			continue;
		}
		if(!@ftp_chdir($con_id, $fullpath)){
			if(@ftp_mkdir($con_id, $part)){
				ftp_chdir($con_id, $part);
			}else{
				return false;
			}
		}
	}
	return true;
}

if(!isset($_SESSION['music_file'])) die('请先上传音频');

$fn = explode('.mp3', basename($_SESSION['music_file']));

$fname = $fn[0] . '.lrc';

$fdir .= '_tm.' . time() . '/'; 

if(!is_dir($music_path . $fdir)) {
	mkdir($music_path . $fdir, 0777, true);
}
$real_file = $music_path . $fdir . $fname;

if(move_uploaded_file($f["tmp_name"], $real_file)) {
	$_o = "{$fdir}{$fname}"; // 临时同步目录 正式要去掉tmp
	
	$conn = ftp_connect("www.kekenet.com") or die('FTP无法连接');
	ftp_login($conn,'uploadlrc','7c#829c4fa85f30$a9') or die('账户密码错误');
	if(!ftp_mkdir_recusive($conn, dirname($_o))) {
		ftp_chdir($conn, '/');
		ftp_mkdir_recusive($conn, dirname($_o));
	}
	
	ftp_put($conn,$fname,$real_file,FTP_BINARY);
	ftp_close($conn);
	
	echo '1';
} else {
	echo '上传时发生错误, 请检查主web服务器文件存储空间是否足够.';
}
